<template>
  <div class="container">
    <div class="form">
      <div class="left-container">
        <div class="logo"></div>
      </div>

      <div class="right-container">
        <h1 class="title">{{ data.title }}</h1>
        <div class="login">
          <div class="optionContent">
            <!-- 安全登录 -->
            <div v-if="data.activeName == 'login'">
              <el-input class="user-input" :prefix-icon="User" v-model="data.user.username" placeholder="账号"></el-input>
              <el-input class="user-input" :prefix-icon="Lock" v-model="data.user.password" placeholder="密码"></el-input>
              <VerifyCode ref="verifyCodeRef" :username="data.user.username" /> <!-- 添加 ref -->
              <el-button class="login-btn" type="primary" @click="handleLogin">登录</el-button>
            </div>

            <!-- 免费注册 -->
            <div v-if="data.activeName == 'register'">
              <el-input class="user-input" v-model="data.user.password" maxlength="15" type="password" placeholder="新密码"
                show-password @blur="validatePassword" />
              <el-input class="user-input" v-model="data.user.confirmPassword" maxlength="15" placeholder="确认密码"
                show-password />
              <VerifyPhone />
              <el-button class="login-btn" type="primary" @click="handleRegister">立即注册</el-button>
            </div>

            
          <!-- 忘记密码 -->
          <div v-if="data.activeName == ''">
            <div v-if="data.isShow===false">
                <el-input class="user-input" :prefix-icon="User" v-model="data.user.username" placeholder="请输入手机号"></el-input>
                <el-input class="user-input" id="captcha-btn" :prefix-icon="Lock" v-model="data.user.captcha" placeholder="请输入验证码" style="width: 65%;"></el-input>
                <el-button  type="primary" round  id="captcha" v-model="data.captcha" :disabled="data.isCounting" @click="getCaptcha">
                    {{
                      data.isCounting 
                      ? `${data.countdown}秒后重新获取` 
                      : '获取验证码'
                    }}
                </el-button>
                <!-- 显示验证码 -->
                <div v-if="data.captcha" class="captcha-display">验证码：{{ data.captcha }}</div>
                <div class="button-group">
                  <!-- 根据验证结果禁用按钮 -->
                  <el-button class="login-btn" type="primary" @click="wjmethods">下一步</el-button>
                </div>
            </div>
            <div v-else>
                <el-input class="user-input" :prefix-icon="Lock" v-model="data.user.password" placeholder="请输入新密码"></el-input>
                <el-input class="user-input" :prefix-icon="Lock" v-model="data.user.confirmPassword" placeholder="请再次确认新密码"></el-input>            
                <el-button class="password-btn" type="primary"  style="margin-top: 82px;" @click="confrim">确认</el-button>
                <el-button class="password-btn" type="primary" style="margin-top: 82px;"  @click="cancel">取消</el-button>
            </div>
          </div>

          <!-- 忘记账号名
          <div v-if="data.activeName == 'wjc'">
            <el-input class="user-input" :prefix-icon="User" v-model="data.user.username" placeholder="账号"></el-input>
            <VerifyCode ref="verifyCodeRef" :username="data.user.username" /> <-- 添加 ref -->
            <!-- <el-button class="login-btn" type="primary" @click="handleLogin">登录</el-button>
          </div> -->
          </div> 

          <!-- 功能区 -->
          <div class="tabs-container">
            <el-tabs v-model="data.activeName" class="demo-tabs" @tab-click="handleClick">
              <el-tab-pane label="忘记密码" name=""></el-tab-pane>
              <!-- <el-tab-pane label="忘记账号名" name="wjc"></el-tab-pane> -->
              
              <el-tab-pane label="免费注册" name="register"></el-tab-pane>
              <el-tab-pane label="安全登录" name="login"></el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { isShallow, onMounted, reactive, ref } from 'vue';
import { User, Promotion, Lock, View, MessageBox } from "@element-plus/icons-vue";
import VerifyCode from '@/components/VerifyCode.vue'
import VerifyPhone from '@/components/VerifyPhone.vue';
import { login, register,getUser, ForgotPassword } from '@/api/login';
import router from '@/router';
import { ElMessage } from 'element-plus';
import { useUserInfoStore } from '@/stores/user';


const data = reactive({
  user: {},             // 登录信息
  activeName: '',
  title: '',
  login: {},            // 登录信息  
  isRegister: false,

  captcha: '',          // 验证码
  isShow: false,        // 是否显示 密码修改
  countdown: 0,     // 验证码剩余时间
  timer: null,         // 定时器
  isCounting: false,    //是否正在倒计时

  
  storedUsername: '',    // 用于存储用户名
})

const wjmethods = () => {
  
   // 先校验手机号格式
    if (!/^1[3-9]\d{9}$/.test(data.user.username)) {
      ElMessage.warning('请输入有效手机号')
      return
    }
  if (!data.user.captcha) {
    ElMessage({
      type: 'warning',
      message: '请输入验证码',
    });
    return;
  }
  
   getUser(data.user.username).then(res => {
    if (res) {
      data.isShow = true
      data.user.password = ''
      data.user.confirmPassword = ''
    } else {
      ElMessage({
        type: 'warning',
        message: '验证码错误或者用户不存在',
      });
    }
  })
  
}
 // 点击确定以后进行密码修改
 const confrim = () =>{
  data.storedUsername= data.user.username

  if (data.user.password === data.user.confirmPassword) {
    ForgotPassword(data.user).then(res => {
      if (res) {
        console.log(res);
        ElMessage({
          type: 'success',
          message: '修改成功,请记好修改后的密码',
        }); 
      }
      data.isShow = false
      data.password = ''
      data.confirmPassword = ''
      data.activeName = 'login'
      data.title = '安全登录'
      data.user = {}
    }).catch(err => {
      console.log(err);
      ElMessage({
        type:'error',
        message: '修改失败',
      });
    }) 
  }
 }

const getCurrentCaptcha = () => {
  return Math.floor(Math.random() * 9000).toString();
}

const cancel = () => {
  //点击取消会返回上一步同时清空表单
  data.isShow = false
}

const getCaptcha = () => {
  if (!data.user.username) {
    ElMessage({
      type: 'warning',
      message: '请输入手机号',
    });
    return;
  }

    // 存储用户名到专门的变量中
    data.storedUsername = data.user.username;

  //获取验证码，这里缺少一个api接口
  data.captcha = getCurrentCaptcha();
  data.isCounting = true;
  data.countdown = 60;
  data.timer = setInterval(() => {
    if (data.countdown > 0) {
      data.countdown--;
    } else {
      clearInterval(data.timer);
      data.isCounting = false;
      data.captcha = ''; // 倒计时结束清空验证码
    }
  }, 1000);
}


// 切换 模式 --->  忘记密码 忘记账号 名免费注册 安全登录
const handleClick = (tab, event) => {
  data.user = {}
  data.login = {}
  data.activeName = tab.props.name
  data.title = tab.props.label
   // 如果切换到非忘记密码的标签页，清空密码相关字段
    if (tab.props.name !== '') {
    data.isShow = false
    data.user.password = ''
    data.user.confirmPassword = ''
  }
}


const verifyCodeRef = ref(null)                      // 引用子组件 verifyCodeRef

// 登录
const handleLogin = async () => {
  if (verifyCodeRef.value.validate() == true) {
    const response = await login(data.user)
    if (response.code == '500' || response.code != '200') {
       ElMessage({
          type: 'warning',
          message: response.msg,
        })
      return
    }

    const userInfoStore = useUserInfoStore()
    userInfoStore.setUser(response.data)

    router.push({ path: '/home' })

    localStorage.setItem('token', JSON.stringify(response.data.token))
  } else {
    ElMessage({
      type: 'warning',
      message: '输入的验证码有误',
    })
  }
}

// 注册
const handleRegister = () => {
  if(!data.isRegister) {
    return
  }
  if (data.user.password === data.user.confirmPassword) {
    data.login.password = data.user.password
    console.log(data.login);
    register(data.login).then(res => {
      console.log(res)
    })
  } else {
    ElMessage({
      type: 'warning',
      message: '密码不一致'
    })
    data.isRegister = true
  }
}

const validatePassword = () => {
  // 确保 data 和 data.user 都已定义
  if (!data || !data.user || data.user.password === undefined) {
    return
  }

  const password = data.user.password

  const hasUpperCase = /[A-Z]/.test(password)

  const hasLowerCase = /[a-z]/.test(password)

  const hasNumber = /[0-9]/.test(password)

  const hasSpace = /\s/.test(password)

  const isValidLength = password.length >= 8 && password.length <= 15

  const validTypesCount = (hasUpperCase ? 1 : 0) + (hasLowerCase ? 1 : 0) + (hasNumber ? 1 : 0)

  if (!isValidLength || validTypesCount < 2 || hasSpace) {
    ElMessage({
      type: 'warning',
      message: '密码长度为8-15位，需包含大写字母、小写字母、数字中的两种或以上，不允许有空格',
    })
    data.isRegister = false
    return
  }

  data.isRegister = true
}
 onMounted(() => {
  if(data.timer)clearInterval(data.timer) 
 })

onMounted(() => {
  data.countdown = 0;
  data.isCounting = false;
})
</script>


<style scoped>
.button-group {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 35px;
}

.container {
  width: 100%;
  height: 100vh;
  background: gray;
  display: flex;
  justify-content: center;
  align-items: center;
  background: radial-gradient(circle at center, #04AFD4 0%, #8BD3E6 100%);
}

.form {
  width: 65%;
  height: 60vh;
  display: flex;
  background: lightblue;
  border-radius: 12px;
}

/* 左侧 */
.left-container {
  flex: 1;
  background: radial-gradient(circle at center, #0389B0 0%, #5DB8D6 100%);
  border-top-left-radius: 12px;
  border-bottom-left-radius: 12px;
}

.logo {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-image: url('../assets/monitoring.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

/* 右侧 */
.right-container {
  flex: 1;
  background-color: #FFFFFF;
  border-top-right-radius: 12px;
  border-bottom-right-radius: 12px;
}

.title {
  margin-top: 15%;
  text-align: center;
}

.login {
  box-sizing: border-box;
  padding: 15px 67px;
}

.el-input {
  height: 35px;
  margin-bottom: 22px;
}

.login-btn {
  width: 100%;
  height: 45px;
  padding: 5px;
  background: linear-gradient(to left, #47ADCD, #87D2E6);
  box-sizing: border-box;
  border-radius: 18px;
  margin-top: 50px;
}
.password-btn {
  width: 40%;
  height: 45px;
  padding: 5px;
  background: linear-gradient(to left, #47ADCD, #87D2E6);
  box-sizing: border-box;
  border-radius: 18px;
  margin-top: 25px;
  margin-left: 20px;
}
.tabs-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.demo-tabs {
  width: 76%;
}

.optionContent {
  height: 270px;
}
#captcha {
  width: 32%;
  height: 35px;
  padding: 5px;
  background-color: white;
  color: #47ADCD; 
  /* background: linear-gradient(to left, #47ADCD, #87D2E6); */
  box-sizing: border-box;
  border: #47ADCD 1px solid;
  border-radius: 18px;
  margin-top: -20px;
  margin-left: 10px;
}
#captcha-btn{
  width: 50%;
}
.captcha-display {
  margin-top: 10px;
  color: #666;
  position: absolute; 
  top: 0;             
  right: 0;           
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 35px;
  position: relative;  
}
</style>